﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


namespace TranTekBE.Trac_Nghiem
{
    public partial class Trac_Nghiem_Hang_Ngay : PageRequireLogin
    {
        public int ThongKeId;
        public Database database = new Database(TinyLib.GetConfigKey("ConnectionString2"));
        protected void Page_Load(object sender, EventArgs e)
        {
            LabelMessage.Text = "";
            //kiem tra xem ngay hom nay co thong ke chua, chua co tao lien
            ThongKeId = GetThongKeId();
            if (!IsPostBack)
            {
                if (ThongKeId > 0)
                {
                    //kiem tra danh sach thong ke chi tiet xem tra loi dc cau nao roi
                    DataTable dt = GetChiTietThongKe();
                    var model = dt.AsEnumerable().Select(c => new
                    {
                        ChiTietId = c.Field<int>("ThongKeChiTietId"),
                        QuestionId = c.Field<int>("QuestionId"),
                        ThongKeId = c.Field<int>("ThongKeId"),
                        Result = c.Field<int>("Result"),
                    }).ToList();
                    //nếu tra lời hết 10 cau rồi thì return
                    if (model.Where(c => c.Result != 0).Count() >= 10)
                    {//return 
                        LiteralChuyenDe.Visible = false;
                        string sql = @"UPDATE tbl_DailyThongKe SET [IsFinish]=1 WHERE UserId='{0}' AND DateCode ={1};UPDATE [tbl_LichLamViec] SET [IS_FINISH_Q]=1 WHERE [ID_USER]='{0}' AND  NGAY_THEM_VAO='{2}'";
                        sql = string.Format(sql, UserInfo.UserID, DateTime.Now.ToString("yyyyMMdd"), DateTime.Now.ToString("yyyy-MM-dd"));
                        database.ExecuteQuery(sql);
                        LiteralQuestion.Text = "Bạn đã hoàn thành xong phần câu hỏi của ngày hôm nay. Hãy quay lại vào ngày mai. Kết quả đúng "+model.Count(c=>c.Result>0)+"/10";
                        return;
                    }

                    LiteralStt.Text = "Câu&nbsp;" + (model.Where(c => c.Result != 0).Count() + 1) + ":&nbsp;";

                    //danh sach cac cau chua tra loi
                    var list = model.Where(c => c.Result == 0);
                    if (list.Count() > 0)
                    {
                        //new co thi lay lai cau hoi do
                        GetQuestionById(list.First().QuestionId.ToString());
                    }
                    else
                    {
                        //khong co thi tạo mới
                        GetRandomQuestion();
                    }
                }
            }
        }
        int GetThongKeId()
        {
            string datecode = DateTime.Now.ToString("yyyyMMdd");
            var ds = database.ExecuteQuery("SELECT * FROM tbl_DaiLyThongKe WHERE DateCode=" + datecode + " AND UserId='" + UserInfo.UserID + "'");
            if (ds.Tables.Count > 0)
            {
                var dt = ds.Tables[0];
                if (dt.Rows.Count > 0)
                    return int.Parse(dt.Rows[0]["ThongKeId"].ToString());
            }
            return InsertToThongKe();
        }
        void GetRandomQuestion()
        {

            string sqlNew = string.Format("SELECT QuestionId FROM tbl_DailyQuestion WHERE QuestionId NOT IN (SELECT QuestionId FROM tbl_DailyThongKeChiTiet WHERE ThongKeId={0} )", ThongKeId);
            var ds = database.ExecuteQuery(sqlNew);
            if (ds.Tables.Count > 0)
            {
                var dt = ds.Tables[0];
                int index = new Random().Next(0, dt.Rows.Count);

                InsertChiTietThongKe(dt.Rows[index]["QuestionId"].ToString());
                hfQuestionId.Value = dt.Rows[0]["QuestionId"].ToString();
                GetQuestionById(dt.Rows[index]["QuestionId"].ToString());
            }
        }
        void GetQuestionById(string questionId)
        {
            hfQuestionId.Value = questionId;
            var ds = database.ExecuteQuery("SELECT q.*, c.Name FROM tbl_DailyQuestion AS q join tbl_DailyCategory as c on q.CategoryId=c.CategoryId WHERE q.QuestionId=" + questionId);
            if (ds.Tables.Count > 0)
            {
                var dt = ds.Tables[0];
                LiteralCategory.Text = dt.Rows[0]["Name"].ToString();
                LiteralQuestion.Text = dt.Rows[0]["Content"].ToString();

                var dsAnswer = database.ExecuteQuery("select * from tbl_DailyAnswer where QuestionId =" + questionId);
                if (dsAnswer.Tables.Count > 0)
                {
                    var dtAnswer = dsAnswer.Tables[0];
                    if (dtAnswer.Rows.Count > 0)
                    {
                        rblDapAn.Items.Clear();
                        rblDapAn.DataSource = dtAnswer;
                        rblDapAn.DataTextField = "Content";
                        rblDapAn.DataValueField = "AnswerId";
                        rblDapAn.DataBind();
                    }
                }
            }
        }
        DataTable GetChiTietThongKe()
        {
            var ds = database.ExecuteQuery("SELECT * FROM tbl_DaiLyThongKeChiTiet WHERE ThongKeId=" + ThongKeId);
            DataTable dt = new DataTable();
            if (ds.Tables.Count > 0)
            {
                dt = ds.Tables[0];
            }
            return dt;
        }

        int InsertToThongKe()
        {
            string sql = string.Format("INSERT INTO tbl_DailyThongKe (UserId,DateCode,CreatedDate) VALUES('{0}',{1},'{2}');SELECT SCOPE_IDENTITY()", UserInfo.UserID, DateTime.Now.ToString("yyyyMMdd"), DateTime.Now);
            return ThuVien.FunctionsUtils.ConvertToInt(database.ExecuteScalar(sql).ToString(), 0);
        }
        void InsertChiTietThongKe(string questionId)
        {
            string sql = string.Format("INSERT INTO tbl_DailyThongKeChiTiet (QuestionId,ThongKeId,Result,StartDate) VALUES({0},{1},0,'{2}')", questionId, ThongKeId, DateTime.Now);
            database.ExecuteQuery(sql);
        }

        bool CheckIsFirst()
        {
            for (int i = 0; i < rblDapAn.Items.Count; i++)
            {
                if (!rblDapAn.Items[i].Enabled)
                    return false;
            }
            return true;
        }
        protected void rblDapAn_SelectedIndexChanged(object sender, EventArgs e)
        {
            string answerId = rblDapAn.SelectedValue;
            var ds = database.ExecuteQuery("SELECT * FROM tbl_DailyAnswer WHERE AnswerId=" + answerId);
            var dt = ds.Tables[0];
            if (dt.Rows[0]["IsTrue"].ToString() == "1")//chọn đúng rồi
            {
                if (CheckIsFirst())
                {
                    string sql = string.Format("UPDATE tbl_DailyThongKeChiTiet SET AnswerId={0},EndDate='{3}',Result=1 WHERE QuestionId={1} AND ThongKeId={2}", answerId, hfQuestionId.Value, ThongKeId, DateTime.Now);
                    database.ExecuteQuery(sql);
                    Response.Redirect(HttpContext.Current.Request.Url.AbsoluteUri);
                }
                else
                {
                    Response.Redirect(HttpContext.Current.Request.Url.AbsoluteUri);
                }
            }
            else
            { //chọn sai
                string sql1 = string.Format(" UPDATE tbl_DailyThongKeChiTiet SET Result=(SELECT Result  FROM tbl_DailyThongKeChiTiet WHERE ThongKeId={0} AND QuestionId={1})-1 WHERE QuestionId={1} AND ThongKeId={0};SELECT Result  FROM tbl_DailyThongKeChiTiet WHERE ThongKeId={0} AND QuestionId={1}", ThongKeId, hfQuestionId.Value);
                if (CheckIsFirst())
                {
                    sql1 = string.Format("UPDATE tbl_DailyThongKeChiTiet SET EndDate='{2}' WHERE ThongKeId={0} AND QuestionId={1}; UPDATE tbl_DailyThongKeChiTiet SET AnswerId={3}, Result=(SELECT Result  FROM tbl_DailyThongKeChiTiet WHERE ThongKeId={0} AND QuestionId={1})-1 WHERE QuestionId={1} AND ThongKeId={0};SELECT Result  FROM tbl_DailyThongKeChiTiet WHERE ThongKeId={0} AND QuestionId={1}", ThongKeId, hfQuestionId.Value, DateTime.Now, answerId);
                }
                int aId = ThuVien.FunctionsUtils.ConvertToInt(database.ExecuteScalar(sql1).ToString(), 0);
                rblDapAn.Items[rblDapAn.SelectedIndex].Enabled = false;
                LabelMessage.Text = "Bạn đã chọn sai lần " + aId * -1 + ". Hãy tiếp tục chọn để tìm ra đáp án";


                //if (aId == -1)
                //    LabelMessage.Text = "Bạn đã chọn sai lần 1. Hãy tiếp tục chọn để tìm ra đáp án";
                //if (aId == -2)
                //    LabelMessage.Text = "Bạn đã chọn sai lần 2. Hãy tiếp tục chọn để tìm ra đáp án";
                //if (aId == -3)
                //    LabelMessage.Text = "Bạn đã chọn sai lần 3. Hãy tiếp tục chọn để tìm ra đáp án";

            }
            UpdateDiemTracNghiem();
        }

        public void UpdateDiemTracNghiem()
        {
            DataTable dt = GetChiTietThongKe();
            var model = dt.AsEnumerable().Select(c => new
            {
                ChiTietId = c.Field<int>("ThongKeChiTietId"),
                QuestionId = c.Field<int>("QuestionId"),
                ThongKeId = c.Field<int>("ThongKeId"),
                Result = c.Field<int>("Result"),
            }).ToList();
            var diem = model.Count(c => c.Result > 0);
            var s = @"UPDATE [tbl_LichLamViec] SET [DiemTracNghiem]={0} WHERE [ID_USER]='{1}' AND  NGAY_THEM_VAO='{2}'";
            var sql = string.Format(s, diem, UserInfo.UserID, DateTime.Now.ToString("yyyy-MM-dd"));
            database.ExecuteQuery(sql);

        }
    }
}